#include <iostream>
#include "Sock.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"

using namespace nc_protocol;

static void Usage(const std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverip serverport\n"
              << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    Sock sock;
    int clientsock = sock.Socket();
    if (!sock.Connect(clientsock, serverip, serverport))
    {
        logMessage(FATAL, "connect error");
        exit(2);
    }
    std::string retStr;
    bool quit = false;
    while (!quit)
    {
        // 1. 获取需求
        Request req;
        std::cout << "请输入#";
        std::cin >> req._x >> req._rule >> req._y;
        // 2. 序列化
        
        std::string s = req.serialization();
        std::string temp = s;
        // 3. 添加长度报头
        s = Encode(s);
        // 4.发送给服务器
        Send(clientsock, s);
        while (true)
        {
            bool ret = Recv(clientsock, &retStr);
            if (!ret)
            {
                quit = true;
                break;
            }
            std::string package = Decode(retStr);
            if (package.empty())
                continue;
            Response res;
            res.Deserialization(package);
            std::string err;
            switch (res._code)
            {
            case 1:
                err = "除零错误";
                break;
            case 2:
                err = "模零错误";
                break;
            case 3:
                err = "其他错误";
                break;
            default:
                std::cout << temp << " = " << res._result << " [success]" << std::endl;
                break;
            }
            if (!err.empty())
                std::cout << err << std::endl;

            break;
        }
    }
    close(clientsock);
    return 0;
}